package com.mf.morefun.ui.moreread;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.ListenBean;
import com.mf.morefun.bean.LocalListenBean;
import com.mf.morefun.bean.MfPicaudioRelListBean;
import com.mf.morefun.bean.MfimgListBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestListenBean;
import com.mf.morefun.service.ListenTeacherService;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.DownloadUtils;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.SendStarOrFlowerNet;
import com.mf.morefun.widget.GlideRoundTransform;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.support.constraint.Constraints.TAG;

public class ListenTeacherActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.vp_info)
    ViewPager vpInfo;
    @BindView(R.id.pb_speed)
    ProgressBar pbSpeed;
    @BindView(R.id.iv_idea)
    ImageView ivIdea;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.iv_reListen)
    ImageView ivReListen;
    @BindView(R.id.ly_content)
    LinearLayout lyContent;
    private DbManager manager;
    private String bookName = "";
    private List<View> viewContains = new ArrayList<View>();//viewpager容器
    private int currentPosition = 0;
    private MyPagerAdapter myPagerAdapter;
    private int totalPage = 0;
    private ListenTeacherService mListenTeacherService = null;
    private List<LocalListenBean> mLocalViewList = new ArrayList<>();//重新创建一个集合来存排序好的集合
    private String pointImg = "";
    private PopupWindow mPointImgPop = null;
    private RoundProcessDialog dialog;
    private SendStarOrFlowerNet mSendStartOrFlowerNet;
    private ListenBean mListenBean;
    private String userId = "";
    private boolean isCanPlay = true;
    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;
    private SPUtils mSPUtils;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_listenteacher;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSPUtils = new SPUtils(ListenTeacherActivity.this);
        powerManager = (PowerManager)this.getSystemService(this.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock1");
        userId = getIntent().getStringExtra(Configuration.USERID);
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSPUtils.getString(Configuration.USERPHONE), mSPUtils.getString(Configuration.USERPASSWORD));
        }
        dialog = new RoundProcessDialog(ListenTeacherActivity.this, "");
        EventBus.getDefault().register(this);
        manager = x.getDb(MoreFunApplication.daoConfig);
        if (StringUtils.isEmpty(getIntent().getStringExtra("BOOKNAME"))) {
            bookName = "" + System.currentTimeMillis();
        } else {
            bookName = getIntent().getStringExtra("BOOKNAME") + "teacher";
        }
        mListenBean = (ListenBean) getIntent().getSerializableExtra("LISTENBEAN");
        if (null != mListenBean){
            setTeacherData(mListenBean);
        }
        ivReListen.getBackground().setAlpha(100);
        ivIdea.getBackground().setAlpha(100);
    }

    private void setTeacherData(ListenBean mListenBean){
        pointImg = mListenBean.getPointImg();
        //只有一条
        if (!StringUtils.isEmpty(mListenBean.getMfimgList()) && !StringUtils.isEmpty(mListenBean.getMfPicaudioRelList())) {
            List<MfimgListBean> mfimgListBeanList = JSON.parseArray(mListenBean.getMfimgList(), MfimgListBean.class);
            List<MfPicaudioRelListBean> mfPicaudioRelListBeanList = JSON.parseArray(mListenBean.getMfPicaudioRelList(), MfPicaudioRelListBean.class);
            //两个集合必须都不为空
            if (null != mfimgListBeanList && mfimgListBeanList.size() > 0 && null != mfPicaudioRelListBeanList && mfPicaudioRelListBeanList.size() > 0) {
                //必须等于  因为一对一
                if (mfimgListBeanList.size() == mfPicaudioRelListBeanList.size()) {
                    //组装成自己的对象
                    List<LocalListenBean> mLocalList = new ArrayList<>();
                    for (int i = 0; i < mfimgListBeanList.size(); i++) {
                        LocalListenBean localListenBean = new LocalListenBean();
                        localListenBean.setImageUrl(mfimgListBeanList.get(i).getAddress());
                        localListenBean.setLocalListenUrl("");
                        localListenBean.setNetListenUrl(mfPicaudioRelListBeanList.get(i).getListen().getAudio());
                        localListenBean.setVodStart(mfPicaudioRelListBeanList.get(i).getVodStart());
                        localListenBean.setMusicName(bookName);
                        localListenBean.setId(0);
                        mLocalList.add(localListenBean);
                    }
                    //先判断是否要去下载 本地有了就不需要下载
                    showLocalList(mLocalList);
                }
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(ListenTeacherActivity.this);
                    errorPop.showPop("");
                    break;
                case 100:
                    vpInfo.setCurrentItem(currentPosition);
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mListenTeacherService) {
            mListenTeacherService.stop();
        }
        MoreFunApplication.isOut = true;//退出
        EventBus.getDefault().unregister(this);
        if (null != mSendStartOrFlowerNet) {
            mSendStartOrFlowerNet.stopAnim();
        }
    }

    private void showLocalList(List<LocalListenBean> mLocalList) {
        try {
            List<LocalListenBean> localList = manager.selector(LocalListenBean.class).where("netListenUrl", "==", mLocalList.get(0).getNetListenUrl()).findAll();
            if (null != localList && localList.size() > 0) {
                manager.delete(localList);
                removeDuplicate(localList);
                List<LocalListenBean> mNeedList = new ArrayList<>();
                for (int i = 0; i < localList.size(); i++) {
                    manager.save(localList.get(i));
                    if (mLocalList.get(0).getNetListenUrl().equals(localList.get(i).getNetListenUrl())) {
                        mNeedList.add(localList.get(i));//拿到存在本地的
                    }
                }
                if (null != mNeedList && mNeedList.size() > 0) {
                    //这里拿到集合可以直接播放
                    ablePlay(mNeedList);
                } else {
                    //这里需要去下载
                    needDownload(mLocalList);
                }
            } else {
                //这里肯定是要去下载
                needDownload(mLocalList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeDuplicate(List<LocalListenBean> localMessageList) {
        List<LocalListenBean> newList = new  ArrayList<LocalListenBean>();
        for(LocalListenBean msg : localMessageList){
            if (newList.size() > 0){
                if (!isSure(newList, msg.getImageUrl())){
                    newList.add(msg);
                }
            }else {
                newList.add(msg);
            }
        }
        localMessageList.clear();
        localMessageList.addAll(newList);
    }

    private boolean isSure(List<LocalListenBean> newList, String imageUrl) {
        boolean isHave = false;
        for (LocalListenBean newMsg : newList){
            if (newMsg.getImageUrl().equals(imageUrl)){
                isHave = true;
            }
        }
        return isHave;
    }


    //需要去下载的集合
    private void needDownload(List<LocalListenBean> mLocalList) {
        DownloadUtils.getsInstance().setListener(new DownloadUtils.OnDownloadListener() {
            @Override
            public void onDowload(String mp3Url) {
                //把本地地址加上 存进入数据库
                insertDb(mp3Url, mLocalList);
                ablePlay(mLocalList);
            }

            @Override
            public void onFailed(String error) {
                ToastUtils.show(getApplicationContext(), "下载失败", 100);
            }
        }).download(mLocalList.get(0));
    }

    private void insertDb(String mp3Url, List<LocalListenBean> mLocalList) {
        try {
            for (int i = 0; i < mLocalList.size(); i++) {
                mLocalList.get(i).setLocalListenUrl(mp3Url);
                manager.save(mLocalList.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //能够播放的集合   但是还要调整集合顺序
    private void ablePlay(List<LocalListenBean> mNeedList) {
        //先初始化一个集合  排序
        getVodStartList(mNeedList, mLocalViewList);
        //同时还要展示viewpager
        showViewPager(mLocalViewList);
    }

    private void getVodStartList(List<LocalListenBean> mNeedList, List<LocalListenBean> mLocalList) {
        double mVodArray[] = new double[mNeedList.size()];
        for (int i = 0; i < mNeedList.size(); i++) {
            mVodArray[i] = mNeedList.get(i).getVodStart();
        }
        //冒泡排序一下
        bubbleSort(mVodArray);
        for (int i = 0; i < mVodArray.length; i++) {
            //取到对象
            getNeedBean(mVodArray[i], mNeedList, mLocalList);
        }
    }

    private void getNeedBean(double vod, List<LocalListenBean> mNeedList, List<LocalListenBean> mLocalList) {
        for (int i = 0; i < mNeedList.size(); i++) {
            if (vod == mNeedList.get(i).getVodStart()) {
                mLocalList.add(mNeedList.get(i));
            }
        }
    }

    private void bubbleSort(double[] mVodArray) {
        for (int i = 0; i < mVodArray.length - 1; i++) {
            for (int j = 0; j < mVodArray.length - 1 - i; j++) {
                if (mVodArray[j] > mVodArray[j + 1]) {
                    double temp;
                    temp = mVodArray[j];
                    mVodArray[j] = mVodArray[j + 1];
                    mVodArray[j + 1] = temp;
                }
            }
        }
    }

    //开始进行播放展示图片
    private void showViewPager(List<LocalListenBean> mLocalList) {
        viewContains.clear();
        currentPosition = 0;
        setPagerAdapter();
        setPagerListener();
        if (null != mLocalList && mLocalList.size() > 0) {
            totalPage = mLocalList.size();
            for (int i = 0; i < mLocalList.size(); i++) {
                View view = LayoutInflater.from(ListenTeacherActivity.this).inflate(R.layout.layout_advertisement, null);
                ImageView imageView = view.findViewById(R.id.iv_image);
                Glide.with(getApplicationContext()).load(mLocalList.get(i).getImageUrl()).into(imageView);
                viewContains.add(view);
            }
            myPagerAdapter.notifyDataSetChanged();
            setProgressBar(currentPosition);
            MoreFunApplication.isOut = false;//这里是进入
            Intent intent = new Intent();
            intent.setAction("GETMUSICPOSITION");
            intent.setPackage("com.mf.morefun"); //指定启动的是那个应用（lq.cn.twoapp）中的Action(b.aidl.DownLoadService)指向的服务组件
            startService(intent);
            mListenTeacherService = new ListenTeacherService(mLocalList.get(0).getLocalListenUrl());
            mListenTeacherService.play();
        }
    }

    private void setPagerListener() {
        vpInfo.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setProgressBar(position);//更新进度条
                int mPosition = 0;
                if (position == 0) {
                    mPosition = position;
                } else {
                    mPosition = position - 1;
                }
                if (null != mListenTeacherService && null != mListenTeacherService.player && mLocalViewList.size() > 0) {
                    if (position == 0) {
                        mListenTeacherService.player.seekTo(0);
                    } else {
                        mListenTeacherService.player.seekTo((int) (mLocalViewList.get(mPosition).getVodStart() * 1000));
                    }
                    if (isCanPlay){
                        ivPlay.setImageResource(R.mipmap.zanting);
                        mListenTeacherService.goPlay();
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (null != mListenTeacherService){
                mListenTeacherService.pause();
            }
            ivPlay.setImageResource(R.mipmap.bofang);
            if (null != wakeLock){
                wakeLock.release();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (null != wakeLock){
                wakeLock.acquire();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void setProgressBar(int currentPosition) {
        int index = (100 / totalPage);
        if (currentPosition == (totalPage - 1)) {
            pbSpeed.setProgress(100);
        } else {
            pbSpeed.setProgress(index * (currentPosition + 1));
        }
    }

    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return viewContains.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//                ((ViewPager) container).removeView(viewContains.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position %= viewContains.size();
            if (position < 0) {
                position = viewContains.size() + position;
            }
            View view = viewContains.get(position);
            // 如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }


    private void setPagerAdapter() {
        myPagerAdapter = new MyPagerAdapter();
        vpInfo.setAdapter(myPagerAdapter);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_back, R.id.iv_idea, R.id.iv_play, R.id.iv_reListen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_idea://弹出pop
                if (!StringUtils.isEmpty(pointImg)) {
                    try {
                        showPointImgPop(pointImg);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.iv_play:
                if (null != mListenTeacherService && null != mListenTeacherService.player && mLocalViewList.size() > 0) {
                    if (!mListenTeacherService.player.isPlaying()) {
                        ivPlay.setImageResource(R.mipmap.zanting);
                        mListenTeacherService.goPlay();
                        isCanPlay = true;
                    } else if (mListenTeacherService.player.isPlaying()) {
                        mListenTeacherService.pause();
                        ivPlay.setImageResource(R.mipmap.bofang);
                    }
                }
                break;
            case R.id.iv_reListen:
                if (null != mListenTeacherService && null != mListenTeacherService.player && mLocalViewList.size() > 0) {
                    int mPosition = 0;
                    if (vpInfo.getCurrentItem() == 0) {
                        mPosition = 0;
                    } else {
                        mPosition = vpInfo.getCurrentItem() - 1;
                    }
                    if (vpInfo.getCurrentItem() == 0) {
                        mListenTeacherService.player.seekTo(0);
                    } else {
                        mListenTeacherService.player.seekTo((int) (mLocalViewList.get(mPosition).getVodStart() * 1000));
                    }
                    mListenTeacherService.goPlay();
                    ivPlay.setImageResource(R.mipmap.zanting);
                    isCanPlay = true;
                }
                break;
        }
    }

    //弹出框
    private void showPointImgPop(String imgUrl) {
        if (null == mPointImgPop) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.layout_poppointimg, null);
            RelativeLayout rlBg = view.findViewById(R.id.rl_bg);
            rlBg.getBackground().setAlpha(100);
            TextView tv_sure = view.findViewById(R.id.tv_sure);
            tv_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closePop();
                }
            });
            TextView tvYaodian = view.findViewById(R.id.tv_yaodian);
            tvYaodian.setText(bookName + "-要点");
            ImageView ivBg = view.findViewById(R.id.iv_bg);
            //设置图片圆角角度
            RequestOptions options = new RequestOptions().transform(new GlideRoundTransform(mContext, 5));
            Glide.with(mContext).load(imgUrl).listener(new mRequestListener(ivBg)).apply(options).into(ivBg);
            mPointImgPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            mPointImgPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mPointImgPop.setBackgroundDrawable(new BitmapDrawable());
            mPointImgPop.setFocusable(true);
            mPointImgPop.setOutsideTouchable(true);
            mPointImgPop.update();
            mPointImgPop.setAnimationStyle(R.style.PopupAnimaFade);
            mPointImgPop.showAtLocation(view, Gravity.CENTER, 0, 0);
            mPointImgPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mPointImgPop.dismiss();
                    mPointImgPop = null;
                }
            });
        }
    }

    private class mRequestListener implements RequestListener {
        private ImageView ivImg;

        public mRequestListener(ImageView ivImg) {
            this.ivImg = ivImg;
        }

        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            Log.d(TAG, "onException: " + e.toString() + "  model:" + model + " isFirstResource: " + isFirstResource);
            ivImg.setImageResource(R.mipmap.ic_launcher);
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            Log.e(TAG, "model:" + model + " isFirstResource: " + isFirstResource);
            return false;
        }
    }

    ;

    private void closePop() {
        if (null != mPointImgPop) {
            mPointImgPop.dismiss();
            mPointImgPop = null;
        }
    }

    //接受musicService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(EventMessageBean message) {
        if (message.getType() == 0) {
            isCanPlay = false;
            ivPlay.setImageResource(R.mipmap.bofang);
            vpInfo.setCurrentItem(0);
            if (null != mListenBean){
                mSendStartOrFlowerNet = new SendStarOrFlowerNet(ListenTeacherActivity.this, lyContent);
                mSendStartOrFlowerNet.initGetFlower(20
                        , MoreFunApplication.loginBean.getResult().getId(),
                        mListenBean.getId(),
                        "1", "5");
            }
        } else if (message.getType() == 1) {
            ivPlay.setImageResource(R.mipmap.bofang);
            ToastUtils.show(ListenTeacherActivity.this, "音乐文件加载失败", 100);
        } else {
            if (null != mListenTeacherService && null != mListenTeacherService.player && mListenTeacherService.player.isPlaying()) {
                long second = mListenTeacherService.player.getCurrentPosition();
                int position = currentPosition;
                //获得比例
                if (null != mLocalViewList && mLocalViewList.size() > 0) {
                    for (int i = 0; i < mLocalViewList.size(); i++) {
                        if (i == 0) {
                            if (second >= 0 && second < (int) (mLocalViewList.get(i).getVodStart() * 1000)) {
                                currentPosition = 0;
                            }
                        } else if (second >= (int) (mLocalViewList.get(i - 1).getVodStart() * 1000) && second < (int) (mLocalViewList.get(i).getVodStart() * 1000)) {
                            currentPosition = i;
                        }
                    }
                }
                if (position != currentPosition) {
                    mHandler.sendEmptyMessage(100);
//                    if (null != mListenTeacherService && null != mListenTeacherService.player){
//                        mListenTeacherService.pause();
//                        ivPlay.setImageResource(R.mipmap.bofang);
//                    }
                }
            }
        }
    }

    private String formatTime(long time) {
        return formatTime("mm:ss", time);
    }

    private String formatTime(String pattern, long milli) {
        int m = (int) (milli / DateUtils.MINUTE_IN_MILLIS);
        int s = (int) ((milli / DateUtils.SECOND_IN_MILLIS) % 60);
        String mm = String.format(Locale.getDefault(), "%02d", m);
        String ss = String.format(Locale.getDefault(), "%02d", s);
        return pattern.replace("mm", mm).replace("ss", ss);
    }
}
